package com.aeoj.clientmanagement.websocket;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.aeoj.clientmanagement.domain.user.SysUser;
import com.aeoj.clientmanagement.service.SysUserService;
import jakarta.annotation.Resource;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * author: ZSM
 * time: 2025-04-25 15:53
 */
@Component
@ServerEndpoint(value = "/client/room/{token}")  // 这个路径是建立连接时的路径
@Slf4j
public class ChatWebsocketServer {
    private static final Map<Long, Session> sessions = new ConcurrentHashMap<>();
    private static SysUserService sysUserService;
    private SysUser currentUser;
    private Session session;
    @Resource
    public void setSysUserService(SysUserService sysUserService) {
        ChatWebsocketServer.sysUserService = sysUserService;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        JWT jwt = JWTUtil.parseToken(token);
        String userId = jwt.getPayload("userId").toString();
        currentUser = sysUserService.getById(Long.parseLong(userId));
        log.info("websocket 建立连接");
        sessions.put(currentUser.getUserId(), session);
        for (Map.Entry<Long, Session> entry : sessions.entrySet()) {
            send(entry.getKey(), currentUser.getNickName() + " 已进入房间");
        }
    }

    @OnClose
    public void onClose() {
        log.info("websocket 关闭连接");
        sessions.remove(currentUser.getUserId());
    }

    @OnMessage
    public void onMessage(String message) {
        for (Map.Entry<Long, Session> entry : sessions.entrySet()) {
            send(entry.getKey(), message);
        }
    }

    public void send(Long userId, String message) {
        JSONObject msg = new JSONObject();
        msg.set("avatar", currentUser.getAvatar());
        msg.set("nickName", currentUser.getNickName());
        msg.set("content", message);
        msg.set("time", new Date());
        msg.set("userId", currentUser.getUserId());
        sessions.get(userId).getAsyncRemote().sendText(JSONUtil.toJsonStr(msg));
    }
}
